<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %> <%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %> <% String path =
request.getContextPath(); String basePath = request.getScheme() + "://" +
request.getServerName() + ":" + request.getServerPort() + path + "/"; %>
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <base href="<%=basePath%>" />
    <title>茶叶进销存系统 - 新增订单</title>
    <link rel="stylesheet" href="css/global.css" />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
    />
    <style>
      .form-container {
        max-width: 800px;
        margin: 0 auto;
        padding: 20px;
      }
      .form-group {
        margin-bottom: 20px;
      }
      .form-group label {
        display: block;
        margin-bottom: 8px;
        font-weight: 500;
        color: var(--text-regular);
      }
      .form-control {
        width: 100%;
        padding: 10px 15px;
        border: 1px solid var(--border-color);
        border-radius: 4px;
        font-size: 14px;
        transition: all 0.3s;
        background-color: #fff;
      }
      .form-control:focus {
        outline: none;
        border-color: var(--primary-color);
        box-shadow: 0 0 0 2px rgba(139, 158, 107, 0.2);
      }
      .btn-group {
        display: flex;
        justify-content: flex-end;
        gap: 15px;
        margin-top: 30px;
      }
      .tea-icon {
        color: var(--primary-color);
        margin-right: 5px;
      }
      .form-header {
        font-size: 18px;
        color: var(--text-regular);
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 1px solid var(--border-color);
      }
      .alert {
        padding: 10px 15px;
        margin-bottom: 20px;
        border-radius: 4px;
        background-color: #fef0f0;
        color: var(--danger-color);
        border: 1px solid #fde2e2;
      }
      .form-row {
        display: flex;
        gap: 20px;
      }
      .form-col {
        flex: 1;
      }
      .order-items {
        border: 1px solid var(--border-color);
        border-radius: 4px;
        padding: 15px;
        margin-bottom: 20px;
      }
      .item-row {
        display: flex;
        gap: 15px;
        align-items: center;
        margin-bottom: 15px;
        padding: 10px;
        background-color: #f9faf7;
        border-radius: 4px;
      }
      .item-row:last-child {
        margin-bottom: 0;
      }
      .item-select {
        flex: 2;
      }
      .item-input {
        flex: 1;
      }
      .remove-btn {
        background: var(--danger-color);
        color: white;
        border: none;
        padding: 8px 12px;
        border-radius: 4px;
        cursor: pointer;
      }
      .add-item-btn {
        background: var(--primary-color);
        color: white;
        border: none;
        padding: 10px 15px;
        border-radius: 4px;
        cursor: pointer;
        margin-bottom: 15px;
      }
      .total-amount {
        font-size: 18px;
        font-weight: bold;
        color: var(--primary-color);
        text-align: right;
        margin-top: 15px;
      }
    </style>
  </head>
  <body>
    <div class="app-container">
      <!-- 侧边栏 -->
      <div class="sidebar" id="sidebar">
        <div class="sidebar-logo" onclick="toggleSidebar()">
          <span><i class="fas fa-leaf tea-icon"></i> 茶叶进销存系统</span>
        </div>

        <div class="sidebar-menu">
          <div
                  class="menu-item "
                  onclick="location.href='views/home.jsp'"
          >
            <i class="fas fa-home"></i>
            <span>系统首页</span>
          </div>
          <div class="menu-item" onclick="location.href='TeaServlet'">
            <i class="fas fa-coffee"></i>
            <span>茶叶管理</span>
          </div>
          <div class="menu-item" onclick="location.href='CategoryServlet'">
            <i class="fas fa-tags"></i>
            <span>分类管理</span>
          </div>
          <div class="menu-item" onclick="location.href='WarehouseServlet'">
            <i class="fas fa-boxes"></i>
            <span>仓库管理</span>
          </div>
          <div class="menu-item active" onclick="location.href='OrderServlet'">
            <i class="fas fa-receipt"></i>
            <span>订单管理</span>
          </div>
          <div class="menu-item" onclick="location.href='LogisticsServlet'">
            <i class="fas fa-shipping-fast"></i>
            <span>物流管理</span>
          </div>
          <div class="menu-item" onclick="location.href='SupplierServlet'">
            <i class="fas fa-truck"></i>
            <span>供应商管理</span>
          </div>
          <div class="menu-item" onclick="location.href='<%=basePath%>purchase/list'">
            <i class="fas fa-truck"></i>
            <span>采购管理</span>
          </div>
          <div class="menu-item" onclick="location.href='CustomerServlet'">
            <i class="fas fa-users"></i>
            <span>客户管理</span>
          </div>
          <div class="menu-item" onclick="location.href='AddressServlet'">
            <i class="fas fa-map-marker-alt"></i>
            <span>地址管理</span>
          </div>
        </div>
      </div>

      <!-- 主内容区 -->
      <div class="main-content">
        <!-- 顶部导航栏 -->
        <div class="navbar">
          <div class="navbar-left">
            <h3><i class="fas fa-plus-circle tea-icon"></i> 新增订单</h3>
          </div>
          <div class="navbar-right">
            <span><i class="fas fa-user tea-icon"></i> 欢迎，${ username}管理员</span>
            <a href="logout" class="el-link el-link--danger ml-10"
              ><i class="fas fa-sign-out-alt"></i> 退出</a
            >
          </div>
        </div>

        <!-- 内容卡片 -->
        <div class="el-card fade-in">
          <div class="el-card__header">
            <span><i class="fas fa-info-circle tea-icon"></i> 订单信息</span>
          </div>
          <div class="el-card__body">
            <form
              action="OrderServlet?action=add"
              method="post"
              class="form-container"
            >
              <!-- 错误信息显示 -->
              <c:if test="${not empty error}">
                <div class="alert">
                  <i class="fas fa-exclamation-circle"></i> ${error}
                </div>
              </c:if>

              <div class="form-header">
                <i class="fas fa-receipt tea-icon"></i> 基本信息
              </div>

              <div class="form-row">
                <div class="form-col">
                  <div class="form-group">
                    <label for="customer_id"
                      ><i class="fas fa-user tea-icon"></i> 选择客户</label
                    >
                    <select
                      id="customer_id"
                      name="customer_id"
                      class="form-control"
                      required
                    >
                      <option value="">请选择客户</option>
                      <c:forEach items="${customerList}" var="customer">
                        <option value="${customer.customer_id}">
                          ${customer.customer_name} - ${customer.phone}
                        </option>
                      </c:forEach>
                    </select>
                  </div>
                </div>
                <div class="form-col">
                  <div class="form-group">
                    <label for="status"
                      ><i class="fas fa-toggle-on tea-icon"></i> 订单状态</label
                    >
                    <select id="status" name="status" class="form-control">
                      <option value="0" selected>待支付</option>
                      <option value="1">已支付</option>
                    </select>
                  </div>
                </div>
              </div>

              <div class="form-header">
                <i class="fas fa-shopping-cart tea-icon"></i> 订单商品
              </div>

              <div class="order-items">
                <button
                  type="button"
                  class="add-item-btn"
                  onclick="addOrderItem()"
                >
                  <i class="fas fa-plus"></i> 添加商品
                </button>
                <div id="orderItems">
                  <!-- 订单项将通过JavaScript动态添加 -->
                </div>
                <div class="total-amount">
                  订单总金额：¥<span id="totalAmount">0.00</span>
                </div>
              </div>

              <input
                type="hidden"
                id="total_amount"
                name="total_amount"
                value="0"
              />

              <div class="btn-group">
                <button
                  type="button"
                  class="el-button"
                  onclick="history.back()"
                >
                  <i class="fas fa-times"></i> 取消
                </button>
                <button type="submit" class="el-button el-button--primary">
                  <i class="fas fa-save"></i> 保存订单
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <script>
      let itemIndex = 0;
      const teaList = [
          <c:forEach items="${teaList}" var="tea" varStatus="status">
              {id: ${tea.tea_id}, name: '${tea.tea_name}', price: ${tea.price}, unit: '${tea.unit}'}<c:if test="${!status.last}">,</c:if>
          </c:forEach>
      ];

      // 侧边栏收缩状态
      let isCollapsed = false;

      // 切换侧边栏状态
      function toggleSidebar() {
          const sidebar = document.getElementById('sidebar');
          isCollapsed = !isCollapsed;

          if(isCollapsed) {
              sidebar.classList.add('collapsed');
              localStorage.setItem('sidebarCollapsed', 'true');
          } else {
              sidebar.classList.remove('collapsed');
              localStorage.setItem('sidebarCollapsed', 'false');
          }
      }

      function addOrderItem() {
          const orderItems = document.getElementById('orderItems');
          const itemRow = document.createElement('div');
          itemRow.className = 'item-row';
          itemRow.id = 'item-' + itemIndex;

          itemRow.innerHTML = `
              <div class="item-select">
                  <select name="tea_id_${itemIndex}" class="form-control" onchange="updatePrice(${itemIndex})" required>
                      <option value="">请选择茶叶</option>

                  </select>
              </div>
              <div class="item-input">
                  <input type="number" name="quantity_${itemIndex}" class="form-control" placeholder="数量" min="1" step="0.01" onchange="calculateTotal()" required>
              </div>
              <div class="item-input">
                  <input type="number" name="unit_price_${itemIndex}" class="form-control" placeholder="单价" min="0" step="0.01" onchange="calculateTotal()" required readonly>
              </div>
              <div class="item-input">
                  <input type="number" name="subtotal_${itemIndex}" class="form-control" placeholder="小计" readonly>
              </div>
              <button type="button" class="remove-btn" onclick="removeOrderItem(${itemIndex})">
                  <i class="fas fa-trash"></i>
              </button>
          `;

          orderItems.appendChild(itemRow);

          // 动态添加茶叶选项
          const select = itemRow.querySelector(`select[name="tea_id_${itemIndex}"]`);
          teaList.forEach(tea => {
              const option = document.createElement('option');
              option.value = tea.id;
              option.setAttribute('data-price', tea.price);
              option.setAttribute('data-unit', tea.unit);
              option.textContent = `${tea.name} - ¥${tea.price}/${tea.unit}`;
              select.appendChild(option);
          });

          itemIndex++;
      }

      function removeOrderItem(index) {
          const itemRow = document.getElementById('item-' + index);
          if(itemRow) {
              itemRow.remove();
              calculateTotal();
          }
      }

      function updatePrice(index) {
          const select = document.querySelector(`select[name="tea_id_${index}"]`);
          const priceInput = document.querySelector(`input[name="unit_price_${index}"]`);

          if(select.selectedIndex > 0) {
              const selectedOption = select.options[select.selectedIndex];
              const price = selectedOption.getAttribute('data-price');
              priceInput.value = price;
              calculateTotal();
          } else {
              priceInput.value = '';
              calculateTotal();
          }
      }

      function calculateTotal() {
          let total = 0;
          const itemRows = document.querySelectorAll('.item-row');

          itemRows.forEach((row, index) => {
              const quantity = row.querySelector('input[name^="quantity_"]');
              const unitPrice = row.querySelector('input[name^="unit_price_"]');
              const subtotal = row.querySelector('input[name^="subtotal_"]');

              if(quantity && unitPrice && quantity.value && unitPrice.value) {
                  const subtotalValue = parseFloat(quantity.value) * parseFloat(unitPrice.value);
                  subtotal.value = subtotalValue.toFixed(2);
                  total += subtotalValue;
              } else {
                  subtotal.value = '';
              }
          });

          document.getElementById('totalAmount').textContent = total.toFixed(2);
          document.getElementById('total_amount').value = total.toFixed(2);
      }

      // 页面加载时检查状态
      window.onload = function() {
          const savedState = localStorage.getItem('sidebarCollapsed');
          if(savedState === 'true') {
              document.getElementById('sidebar').classList.add('collapsed');
              isCollapsed = true;
          }

          // 默认添加一个订单项
          addOrderItem();

          // 表单提交验证
          document.querySelector('form').addEventListener('submit', function(e) {
              const customerId = document.getElementById('customer_id').value;
              const totalAmount = document.getElementById('total_amount').value;
              const itemRows = document.querySelectorAll('.item-row');

              if(!customerId) {
                  alert('请选择客户');
                  e.preventDefault();
                  return;
              }

              if(itemRows.length === 0) {
                  alert('请至少添加一个商品');
                  e.preventDefault();
                  return;
              }

              if(parseFloat(totalAmount) <= 0) {
                  alert('订单金额必须大于0');
                  e.preventDefault();
                  return;
              }

              // 验证每个订单项
              let hasValidItem = false;
              itemRows.forEach(row => {
                  const teaSelect = row.querySelector('select[name^="tea_id_"]');
                  const quantity = row.querySelector('input[name^="quantity_"]');

                  if(teaSelect.value && quantity.value && parseFloat(quantity.value) > 0) {
                      hasValidItem = true;
                  }
              });

              if(!hasValidItem) {
                  alert('请至少添加一个有效的商品');
                  e.preventDefault();
                  return;
              }
          });
      }
    </script>
  </body>
</html>
